import { _decorator, Component, game, Node } from 'cc';
const { ccclass, property } = _decorator;

import { config, TonAddressConfig } from '../Config';
import { GameFi, TonConnectUI, Address, toNano, TonTransferRequest } from '@ton/cocos-sdk'
import { TelegramWebApp } from '../../cocos-telegram-miniapps/telegram-web';
import { GlobalVar } from '../GlobalVar';
import { GameEvent, PayEvent } from '../EventName';

@ccclass('TonComm')
export class TonComm extends Component{

    private _bTonInit: boolean = false;

    private _cocosGameFi: GameFi;
    private _connectUI;
    private _gameFi: GameFi;
    private serverHost: string = "http://127.0.0.1:8888";
    //ton 和jetton地址， ton是买东西付款到的地址
    private _config: TonAddressConfig;
    protected onLoad(): void {

        game.on(PayEvent.TRANSFER_TON,this.onTransferTon,this);
        this.init();
    }
    init(){

        TelegramWebApp.Instance.init().then(res => {
            console.log("telegram web app init : ", res.success);
        });

        // fetch(`${this.serverHost}/config`, { method: 'GET' }).then(response => {
        //     return response.json();
        // }).then(value => {
        //     console.log("config : ", value);
        //     if (value.ok) {

        //         const addressConfig = {
        //             tonAddress: value.tokenRecipient,
        //             jettonAddress: value.jettonMaster
        //         } as TonAddressConfig;
        //         //this.toolView.setTonAddressConfig(addressConfig);

        //     } else {
        //         console.log('request config failed!');
        //     }
        // });
        // this.loadWallet().then(res => {
        //     if (!res) {
        //         console.error('load wallet failed!')
        //         return;
        //     }
        // }).catch(err => { console.error(err); });

        this._initTonConnect();

    }

    public async openModal() {
        if (!this._bTonInit) return;

        if (this.isConnected()) {
            this._connectUI.disconnect();
        } else {
            this._connectUI.openModal();
        }
    }



    // async loadWallet():Promise<boolean>{
    //     try{
    //   const value =await   fetch(`${config.backendUrl}/config`, {
    //         headers: {
    //             'Content-Type': 'application/json',
    //             'Accept': 'application/json',
    //             "ngrok-skip-browser-warning":"1"
    //         },
    //         method: 'GET'}).then(response => {
    //         return response.json();
    //     })
    //     const addressConfig = {
    //         tonAddress: value.tokenRecipient,
    //         jettonAddress: value.jettonMaster
    //     } as TonAddressConfig;
    //       this._config = addressConfig;
    //     return true;
    // }catch(e){

    //     console.error('request config failed!',e);
    //     return false;
    // }
       
    // }

    public setGameFi(gamefi: GameFi) {
        this._gameFi = gamefi;

        if (this._gameFi && this._gameFi.walletConnector.connected) {
            const address = this._gameFi.walletConnector.account.address;
            //this.addressLab.string = Address.parseRaw(address).toString({ testOnly: true, bounceable: false }).substring(0, 6) + '...';
        } else {
            //this.addressLab.string = 'Unconnected';
        }

        //this.updateTelegramInfo();
    }

    public onTransferTon(value?: number,comment?: string) {
        game.emit(GameEvent.SHOW_TOAST,"open wallet")
        if (this._cocosGameFi && this._cocosGameFi.walletConnector?.connected) {
            let address = Address.parse('UQBhRGJNn4czI3IVoO3mVjiji7oeRHiMQUWPmNSPmeyexOXW')
            console.log(address,"转账真实地址");
            const tonTransferReq = {
                to: address,
                //to: 'UQBhRGJNn4czI3IVoO3mVjiji7oeRHiMQUWPmNSPmeyexOXW',
                amount: toNano(value),
                comment: comment
            } as TonTransferRequest;
            try{

                this._cocosGameFi.transferTon(tonTransferReq);
            }
            catch(e){
                console.log(e,"ton支付失败");
            }
        }else{
            console.log("try openModal")
            this.openModal();
            console.log("openModal success")
        }
    }
    async _initTonConnect() {

        //this.toolView.node.active = false;
        console.log("初始化ton连接")
        //manifestUrl: 'https://helizi2019.github.io/wallet/tonconnect-manifest.json'
        let uiconnector = new TonConnectUI({
            manifestUrl: 'https://game.lastoasis.org/tonconnect-manifest.json'
            //manifestUrl: 'https://ton-connect.github.io/demo-dapp-with-wallet/tonconnect-manifest.json'
            //manifestUrl: 'http://192.168.0.103:7456/web-mobile/web-mobile/tonconnect-manifest.json'
            
        });
        console.log(uiconnector,"uiconnector")
        this._cocosGameFi = await GameFi.create({
            connector: uiconnector
        });
        this._connectUI = this._cocosGameFi.walletConnector;
        console.log(this._connectUI);
        console.log("初始化ton连接成功")
        // const unsubscribeModal = this._connectUI.onModalStateChange(state => {
        //     console.log("model state changed! : ", state);

        //     this.updateConnect();
        // });

        // const unsubscribeConnectUI = this._connectUI.onStatusChange(info => {
        //     console.log("wallet info status changed : ", info);

        //     //this.updateConnect();
        // });

        this._bTonInit = true;
        //this.updateConnect();
    }

    public isConnected(): boolean {
        if (!this._connectUI) {
            console.error("ton ui not inited!");
            return false;
        }
        return this._connectUI.connected;
    }

    private updateConnect() {
        if (this.isConnected()) {
            const address = this._connectUI.account.address;
            //this.connectLabel.string = Address.parseRaw(address).toString({ testOnly: true, bounceable: false }).substring(0, 6) + '...';
        } else {
            //this.connectLabel.string = "Connect";
        }
    }



    
}


